$(function () {

  let $account = $('input[name=telephone]');
  let $password = $('input[name=password]');
  let $remember = $('input[name=remember]');
  let $submit = $('.form-contain');

  $submit.submit(check_submit);              //必须是form表单才能绑定submit事件

  //验证登录时用户名和密码的合法性
  function check_submit(ev) {
    ev.preventDefault();
    //阻止自动提交
    let account = $account.val();
    let password = $password.val();
    let rem_status = $remember.is(":checked");

    if (!(/^1[3-9]\d{9}$/).test(account) && !(/^\w{4,20}$/).test(account)) {
      //判断用户账号信息输入的合法性
      message.showError("用户账号信息不正确，请重新输入");
      return
    }
    if (!password) {
      message.showError("请输入密码");
      return
    }
    if (!(/^\w{6,20}$/).test(password)) {
      message.showError("密码不正确，请重新输入");
      return
    }

    let user_info = {
      'account': account,
      'password': password,
    };
    if (rem_status === true) {
      user_info['remember'] = '1'
    }
    //如果用户勾选了七天免密登录则设置该属性
    $.ajax({
      url: '/user/login/',
      method: 'POST',
      data: JSON.stringify(user_info),
      contentType: 'application/json;charset=utf-8',
      type: 'json',
      async: false
    })
        .done((res) => {
          if (res.no === "0") {
            message.showSuccess(res.msg);
            setTimeout(function () {
              window.location.href='/';
            },2000)
            //登陆成功后跳转到主页
          } else {
            message.showError(res.msg)
          }
        })
        .fail(() => {
          message.showError("服务器异常")
        })
  }
  csrf()

});